<template>
    <div class="lottery-list-container">
        <div class="page-header">
            <h2>抽奖活动管理 <el-tag v-if="autoRefresh" type="success" size="small">自动刷新中</el-tag></h2>
            <div class="header-actions">
                <el-switch v-model="autoRefresh" active-text="自动刷新" inactive-text="手动刷新"
                    @change="handleAutoRefreshChange" />
                <el-button type="primary" :icon="Plus" @click="goToCreate">创建抽奖</el-button>
                <el-button type="info" :icon="Refresh" @click="fetchLotteryList">刷新</el-button>
            </div>
        </div>

        <!-- 搜索和筛选区域 -->
        <div class="search-area">
            <div class="search-item">
                <span class="label">群组:</span>
                <el-select v-model="searchForm.groupId" placeholder="选择群组" clearable @change="handleGroupChange"
                    class="search-input">
                    <el-option v-for="group in groupList" :key="group.groupId" :label="group.name"
                        :value="group.groupId" />
                </el-select>
            </div>
            <div class="search-item">
                <span class="label">状态:</span>
                <el-select v-model="searchForm.status" placeholder="选择状态" clearable @change="handleSearchChange"
                    class="search-input">
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </div>
            <el-button type="primary" :icon="Search" @click="handleSearchChange">搜索</el-button>
        </div>

        <!-- 列表区域 -->
        <el-table :data="lotteryList" v-loading="loading" style="width: 100%">
            <el-table-column prop="title" label="活动名称" min-width="150">
                <template #default="scope">
                    <div class="lottery-title">
                        {{ scope.row.title }}
                        <el-tag v-if="scope.row.isHighlighted" type="warning" size="small" effect="dark">置顶</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="prize" label="奖品" min-width="120" />
            <el-table-column prop="groupName" label="所属群组" min-width="120" />
            <el-table-column prop="participants" label="参与情况" width="120">
                <template #default="scope">
                    <span>{{ scope.row.participantCount || 0 }}/{{ scope.row.maxParticipants }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="winnerCount" label="中奖人数" width="100" />
            <el-table-column prop="pointsCost" label="积分" width="80" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="getStatusType(scope.row.status)">
                        {{ formatStatus(scope.row.status) }}
                    </el-tag>
                    <div v-if="scope.row.drawMode === 'time' && scope.row.status === 'active'" class="timed-draw-info">
                        <el-tooltip>
                            <template #content>
                                <div>定时开奖: {{ formatDate(scope.row.drawAt) }}</div>
                                <div>距开奖还有: {{ formatTimeRemaining(scope.row.drawAt) }}</div>
                            </template>
                            <el-tag type="warning" size="small" effect="plain">⏰</el-tag>
                        </el-tooltip>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="scope">
                    {{ formatDate(scope.row.createdAt) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200">
                <template #default="scope">
                    <el-button v-if="scope.row.status === 'pending'" type="success" size="small"
                        @click="publishLottery(scope.row)">
                        发布
                    </el-button>
                    <el-button v-if="scope.row.status === 'active'" type="primary" size="small"
                        @click="drawLottery(scope.row)">
                        开奖
                    </el-button>
                    <el-button v-if="scope.row.status === 'pending'" type="danger" size="small"
                        @click="cancelLottery(scope.row)">
                        取消
                    </el-button>
                    <el-button type="info" size="small" @click="viewLotteryDetail(scope.row)">
                        详情
                    </el-button>
                    <div v-if="isDev && scope.row.drawMode === 'time' && scope.row.status === 'active'">
                        <el-button type="warning" size="small" @click="debugTimedLottery(scope.row)">
                            调试定时开奖
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container" v-if="total > 0">
            <span class="total-text">共 {{ total }} 条</span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
                layout="prev, pager, next, sizes" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" background />
        </div>

        <!-- 无数据提示 -->
        <el-empty v-if="!loading && lotteryList.length === 0" description="暂无抽奖活动" />
    </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, h } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Refresh, Search } from '@element-plus/icons-vue';
import { getLotteryList, publishLotteryApi, drawLottery as drawLotteryApi, cancelLottery as cancelLotteryApi } from '../../../api/lottery';
import { getGroups } from '../../../api/group';
import { formatDate, formatStatus, getStatusType } from '../../../utils/format';

export default {
    name: 'PointsLottery',
    setup() {
        // 判断是否为开发环境
        const isDev = import.meta.env.MODE === 'development';

        const router = useRouter();
        const loading = ref(false);
        const lotteryList = ref([]);
        const total = ref(0);
        const currentPage = ref(1);
        const pageSize = ref(20);
        const groupList = ref([]);
        const autoRefresh = ref(false);
        let refreshTimer = null;

        const searchForm = reactive({
            groupId: '',
            status: ''
        });

        const statusOptions = [
            { label: '待发布', value: 'pending' },
            { label: '进行中', value: 'active' },
            { label: '已结束', value: 'completed' },
            { label: '已取消', value: 'cancelled' }
        ];

        // 获取群组列表
        const fetchGroups = async () => {
            try {
                const res = await getGroups();
                if (res.data.success) {
                    groupList.value = res.data.data;
                }
            } catch (error) {
                console.error('获取群组列表失败:', error);
                ElMessage.error('获取群组列表失败');
            }
        };

        // 获取抽奖列表
        const fetchLotteryList = async () => {
            loading.value = true;
            try {
                console.log('正在获取抽奖列表...');
                const response = await getLotteryList({
                    page: currentPage.value,
                    limit: pageSize.value,
                    groupId: searchForm.groupId,
                    status: searchForm.status
                });

                console.log('获取到的抽奖列表数据:', response);

                // 正确处理多层嵌套的数据结构
                const res = response.data; // 获取Axios包装的data

                if (res.success) {
                    // 处理后端返回的数据
                    if (res.data && res.data.list) {
                        lotteryList.value = res.data.list.map(item => {
                            // 获取群组名称
                            const groupName = getGroupName(item.groupId);

                            return {
                                ...item,
                                groupName,
                                // 计算参与人数和进度
                                participantCount: item.participantCount || 0,
                                progressPercent: Math.round((item.participantCount / item.maxParticipants) * 100) || 0,
                                // 格式化日期
                                createdAtFormat: formatDate(item.createdAt),
                                startedAtFormat: formatDate(item.startedAt),
                                endedAtFormat: formatDate(item.endedAt)
                            };
                        });

                        // 更新分页信息
                        total.value = res.data.pagination.total || 0;
                    } else {
                        console.error('API返回数据结构不包含list字段:', res);
                        ElMessage.error('获取数据格式异常');
                    }
                } else {
                    ElMessage.error(res.message || '获取抽奖列表失败');
                }
            } catch (error) {
                console.error('获取抽奖列表出错:', error);
                ElMessage.error('获取抽奖列表失败');
            } finally {
                loading.value = false;
            }
        };

        // 根据群组ID获取群组名称
        const getGroupName = (groupId) => {
            const group = groupList.value.find(g => g.groupId === groupId);
            return group ? group.name : groupId;
        };

        // 处理群组变更
        const handleGroupChange = () => {
            currentPage.value = 1;
            fetchLotteryList();
        };

        // 处理搜索条件变更
        const handleSearchChange = () => {
            currentPage.value = 1;
            fetchLotteryList();
        };

        // 查看抽奖详情
        const viewLotteryDetail = (row) => {
            console.log('查看抽奖详情:', row);
            router.push({
                path: `/admin/points/lottery/${row._id}`,
                query: {
                    from: 'list',
                    title: row.title
                }
            });
        };

        // 发布抽奖
        const publishLottery = async (lottery) => {
            try {
                console.log('发布抽奖:', lottery); // 添加调试日志
                if (!lottery || !lottery._id) {
                    ElMessage.error('无效的抽奖活动数据');
                    return;
                }

                await ElMessageBox.confirm('确定要发布该抽奖活动吗？发布后将立即生效。', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });

                const res = await publishLotteryApi(lottery._id);
                if (res && res.data && res.data.success) {
                    ElMessage.success('抽奖活动已发布');
                    fetchLotteryList(); // 刷新列表
                } else {
                    const errorMsg = res?.data?.message || '发布失败，请稍后重试';
                    ElMessage.error(errorMsg);
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('发布抽奖活动失败:', error);
                    ElMessage.error('发布抽奖活动失败');
                }
            }
        };

        // 手动开奖
        const drawLottery = async (lottery) => {
            try {
                await ElMessageBox.confirm(
                    '确定要立即开奖吗？将会立即抽取中奖者。',
                    '开奖确认',
                    {
                        confirmButtonText: '确定开奖',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );

                loading.value = true;
                const response = await drawLotteryApi(lottery._id);

                // 增强错误处理，确保response存在且有正确的数据结构
                if (response && response.data && response.data.success) {
                    ElMessage.success('开奖成功');
                    fetchLotteryList(); // 刷新列表
                } else {
                    // 处理API返回的错误信息
                    const errorMsg = response?.data?.message || '开奖失败，请稍后再试';
                    ElMessage.error(errorMsg);
                }
            } catch (error) {
                console.error('开奖失败:', error);
                // 友好的错误信息处理
                const errorMsg = error.response?.data?.message || '开奖操作失败';
                ElMessage.error(errorMsg);
            } finally {
                loading.value = false;
            }
        };

        // 取消抽奖
        const cancelLottery = async (row) => {
            ElMessageBox.confirm(
                '确定要取消此抽奖活动吗？此操作不可撤销。',
                '取消确认',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'danger'
                }
            ).then(async () => {
                try {
                    const res = await cancelLotteryApi(row._id);
                    if (res.data.success) {
                        ElMessage.success('抽奖活动已取消');
                        fetchLotteryList();
                    } else {
                        ElMessage.error(res.data.message || '取消失败');
                    }
                } catch (error) {
                    console.error('取消抽奖失败:', error);
                    ElMessage.error('取消抽奖失败');
                }
            }).catch(() => {
                // 用户取消操作，不做任何处理
            });
        };

        // 前往创建抽奖页面
        const goToCreate = () => {
            router.push('/admin/points/lottery/create');
        };

        // 处理页码变化
        const handleCurrentChange = (val) => {
            currentPage.value = val;
            fetchLotteryList();
        };

        // 处理每页条数变化
        const handleSizeChange = (val) => {
            pageSize.value = val;
            fetchLotteryList();
        };

        // 自动刷新设置
        const handleAutoRefreshChange = (val) => {
            if (val) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        };

        // 开始自动刷新
        const startAutoRefresh = () => {
            stopAutoRefresh(); // 先确保没有活跃的定时器
            refreshTimer = setInterval(fetchLotteryList, 5000); // 每5秒刷新一次
            ElMessage.success('已开启自动刷新');
        };

        // 停止自动刷新
        const stopAutoRefresh = () => {
            if (refreshTimer) {
                clearInterval(refreshTimer);
                refreshTimer = null;
            }
        };

        // 格式化剩余时间
        const formatTimeRemaining = (targetDate) => {
            if (!targetDate) return '未设置';

            const target = new Date(targetDate);
            const now = new Date();

            if (isNaN(target.getTime())) return '日期无效';

            // 如果时间已过，返回已过期
            if (target < now) return '已过期';

            // 计算剩余时间（毫秒）
            const diff = target.getTime() - now.getTime();

            // 转换为天、小时、分钟
            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

            // 格式化输出
            let result = '';
            if (days > 0) result += `${days}天`;
            if (hours > 0) result += `${hours}小时`;
            if (minutes > 0) result += `${minutes}分钟`;

            return result || '不到1分钟';
        };

        // 调试定时抽奖
        const debugTimedLottery = async (lottery) => {
            if (!isDev) return;

            const remainingTime = formatTimeRemaining(lottery.drawAt);

            try {
                await ElMessageBox.confirm(
                    `此操作仅用于调试！\n\n抽奖ID: ${lottery._id}\n抽奖名称: ${lottery.title}\n开奖时间: ${formatDate(lottery.drawAt)}\n剩余时间: ${remainingTime}\n\n确定要查看定时开奖状态吗？`,
                    '调试定时抽奖',
                    {
                        confirmButtonText: '查看状态',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );

                ElMessage({
                    type: 'info',
                    message: `定时抽奖信息：\n抽奖ID: ${lottery._id}\n开奖时间: ${formatDate(lottery.drawAt)}\n剩余时间: ${remainingTime}\n\n请查看后端日志获取更多信息`,
                    duration: 5000
                });

            } catch (error) {
                // 用户取消操作
            }
        };

        // 组件挂载时获取数据
        onMounted(() => {
            fetchGroups();
            fetchLotteryList();
        });

        // 组件卸载前清理
        onBeforeUnmount(() => {
            stopAutoRefresh();
        });

        return {
            loading,
            lotteryList,
            total,
            currentPage,
            pageSize,
            groupList,
            searchForm,
            statusOptions,
            autoRefresh,
            isDev,
            Plus,
            Refresh,
            Search,
            formatDate,
            formatStatus,
            getStatusType,
            fetchLotteryList,
            handleGroupChange,
            handleSearchChange,
            viewLotteryDetail,
            publishLottery,
            drawLottery,
            cancelLottery,
            goToCreate,
            handleCurrentChange,
            handleSizeChange,
            handleAutoRefreshChange,
            formatTimeRemaining,
            debugTimedLottery
        };
    }
};
</script>

<style scoped>
.lottery-list-container {
    padding: 20px;
    background-color: #fff;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    font-size: 1.5rem;
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}

.search-area {
    margin-bottom: 20px;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
}

.search-item {
    display: flex;
    align-items: center;
}

.search-item .label {
    margin-right: 8px;
    white-space: nowrap;
}

.search-input {
    width: 200px;
}

.lottery-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.total-text {
    margin-right: 16px;
    color: #606266;
}

.timed-draw-info {
    margin-top: 4px;
    display: flex;
    align-items: center;
}
</style>